package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component("crmFormAuthenticationFilter")
public class CrmFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JsonResult jsonResult = new JsonResult();
        //返回成功的信息
        response.setContentType("text/json;charset:UTF-8");//返回类型json数据
        //将json
        response.getWriter().print(JSON.toJSONString(jsonResult));
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        JsonResult jsonResult = new JsonResult(false,"账号或密码错误");
        if(e instanceof UnknownAccountException){
            jsonResult.setMsg("账号不存在");
        }else if (e instanceof IncorrectCredentialsException){
            jsonResult.setMsg("密码错误");
        }
        response.setContentType("text/json;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSONString(jsonResult));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return true;
    }
}
